//
//  CYWebViewPlugin.m
//  cyjf
//
//  Created by tauCross on 2017/5/24.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYWebViewPlugin.h"

#import "CYPublicParameters.h"

#import "CYActionManager.h"
#import "CYShareView.h"

#import <objc/message.h>
#import <TCJSONKit.h>


@implementation CYWebViewPlugin

- (NSArray *)supportActions
{
    return @[@"setShareButtonShow",
             @"setNavigationTitle",
             @"getDeviceInfo",
             @"getUserInfo",
             @"getAuthStatus",
             @"sendAction",
             @"closeWebView",
             @"shareAction"];
}

- (void)callbackWithCallBackID:(id)callbackID code:(NSNumber *)code msg:(NSString *)msg result:(id)result
{
    NSString *callbackJS = [NSString stringWithFormat:@"CYJFBridge.callback('%@', %@, '%@', '%@')", callbackID, code, msg, SAFE_STRING([result tc_JSONString])];
    [self.webViewController.webView evaluateJavaScript:callbackJS completionHandler:nil];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSString *name = message.name;
    NSString *selectorName = [name stringByAppendingString:@"WithParameters:callbackID:"];
    SEL selector = NSSelectorFromString(selectorName);
    if([self respondsToSelector:selector])
    {
        id parameters = nil;
        id callbackID = nil;
        if([message.body isKindOfClass:[NSDictionary class]])
        {
            parameters = message.body[@"parameters"];
            callbackID = message.body[@"callbackID"];
        }
        ((void(*)(id, SEL, id, id))objc_msgSend)(self, selector, parameters, callbackID);
    }
}

- (void)setNavigationTitleWithParameters:(NSString *)parameters callbackID:(id)callbackID
{
    if(parameters.length)
    {
        self.webViewController.navigationItem.title = parameters;
    }
}

- (void)setShareButtonShowWithParameters:(NSNumber *)parameters callbackID:(id)callbackID
{
    if(parameters.boolValue)
    {
        UIImage *image = [CYImage(@"public_nav_share") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
        self.webViewController.navigationItem.rightBarButtonItem = item;
    }
    else
    {
        self.webViewController.navigationItem.rightBarButtonItem = nil;
    }
}

- (void)getDeviceInfoWithParameters:(NSString *)parameters callbackID:(id)callbackID
{
    [self callbackWithCallBackID:callbackID code:@0 msg:@"success" result:[CYPublicParameters standardPublicParameters].dictionary];
}

- (void)getUserInfoWithParameters:(NSString *)parameters callbackID:(id)callbackID
{
    if(CYStandardAuthManager.currentAuth.token.length)
    {
        [self callbackWithCallBackID:callbackID code:@0 msg:@"success" result:@{@"token" : SAFE_STRING(CYStandardAuthManager.currentAuth.token),
                                                                                @"userId" : SAFE_NUMBER(CYStandardAuthManager.currentAuth.uid),
                                                                                @"mobile" : SAFE_STRING(CYStandardAuthManager.currentAuth.mobile)}];
    }
    else
    {
        [self callbackWithCallBackID:callbackID code:@(1) msg:@"用户未登录" result:nil];
    }
}

- (void)getAuthStatusWithParameters:(id)parameters callbackID:(id)callbackID
{
    if(CYStandardAuthManager.currentAuth)
    {
        [self callbackWithCallBackID:callbackID code:@(0) msg:@"用户已登录" result:nil];
    }
    else
    {
        [self callbackWithCallBackID:callbackID code:@(1) msg:@"用户未登录" result:nil];
    }
}

- (void)sendActionWithParameters:(NSDictionary *)parameters callbackID:(id)callbackID
{
    if([parameters isKindOfClass:[NSDictionary class]])
    {
        CYDataAPIActionModel *actionModel = [CYDataAPIActionModel mj_objectWithKeyValues:parameters];
        [CYStandardActionManager executeActionWithModel:actionModel fromViewController:self.webViewController];
    }
}

- (void)closeWebViewWithParameters:(id)parameters callbackID:(id)callbackID
{
    [self.webViewController closeAction];
}

- (void)shareActionWithParameters:(NSDictionary *)parameters callbackID:(id)callbackID
{
    if([parameters isKindOfClass:[NSDictionary class]])
    {
        NSNumber *type = SAFE_NUMBER(parameters[@"type"]);
        CYShareObject *object = [[CYShareObject alloc] init];
        switch(type.integerValue)
        {
            case 1:
                object.type = CYShareTypeURL;
                break;
            default:
                break;
        }
        object.url = SAFE_STRING(parameters[@"url"]);
        object.title = SAFE_STRING(parameters[@"title"]);
        object.detail = SAFE_STRING(parameters[@"detail"]);
        object.thumbURL = [SAFE_STRING(parameters[@"thumb"]) tc_url];
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
            object.thumb = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[SAFE_STRING(parameters[@"thumb"]) tc_url]]];
        });
        @weakify(self);
        CYShareView *shareView = [[CYShareView alloc] init];
        shareView.shareAction = ^(CYShareTarget target) {
            if(object.thumb == nil)
            {
                NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
                NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
                object.thumb = CYImage(icon);
            }
            object.target = target;
            [[CYShareManager standardManager] shareWithObject:object complete:^(BOOL succeed, NSString *error) {
                NSNumber *shareTo = @0;
                switch(target)
                {
                    case CYShareTargetQQ:
                        shareTo = @3;
                        break;
                    case CYShareTargetWechat:
                        shareTo = @1;
                        break;
                    case CYShareTargetWechatTimeLine:
                        shareTo = @2;
                        break;
                    case CYShareTargetWeibo:
                        shareTo = @4;
                        break;
                }
                @strongify(self);
                if(succeed)
                {
                    [self callbackWithCallBackID:callbackID code:@0 msg:@"分享成功" result:@{@"shareTo" : shareTo, @"shareResult" : @1}];
                }
                else
                {
                    [self callbackWithCallBackID:callbackID code:@0 msg:@"分享失败" result:@{@"shareTo" : shareTo, @"shareResult" : @0}];
                }
            }];
        };
        [shareView show];
    }
}

#pragma mark - Actions
- (void)shareAction
{
    @weakify(self);
    
    CYShareObject *object = [[CYShareObject alloc] init];
    object.type = CYShareTypeURL;
    [self.webViewController.webView evaluateJavaScript:@"if(typeof(shareInfo) === 'function') shareInfo();" completionHandler:^(NSString *shareInfoString, NSError * _Nullable error) {
        NSDictionary *shareInfo = [shareInfoString tc_JSONObject];
        if([shareInfo isKindOfClass:[NSDictionary class]])
        {
            object.url = SAFE_STRING(shareInfo[@"url"]);
            object.title = SAFE_STRING(shareInfo[@"title"]);
            object.detail = SAFE_STRING(shareInfo[@"detail"]);
            object.thumbURL = [SAFE_STRING(shareInfo[@"activityLogo"]) tc_url];
            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
                object.thumb = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[SAFE_STRING(shareInfo[@"activityLogo"]) tc_url]]];
            });
        }
    }];

    CYShareView *shareView = [[CYShareView alloc] init];
    shareView.shareAction = ^(CYShareTarget target) {
        @strongify(self);
        if(self)
        {
            if(object.thumb == nil)
            {
                NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
                NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
                object.thumb = CYImage(icon);
            }
            object.target = target;
            [[CYShareManager standardManager] shareWithObject:object complete:nil];
        }
    };
    [shareView show];
}

@end
